<template>
  <el-dialog
      :close-on-click-modal="false"
      :show-close="showCloseIcon"
      :visible="searchFlag"
      class="zdy-dialog" width="75%"
      :title="this.i18n.t('search')"
      :lock-scroll="false"
      :before-close="handleCloseDialog">
<!--    <el-alert-->
<!--        :title="this.i18n.t('Search for unbound devices in the device management table.')"-->
<!--        :closable="false"-->
<!--        show-icon-->
<!--        type="info">-->
<!--    </el-alert>-->

    <div class="">
      <div>
        <el-button size="mini" style="margin-left: 10px" v-if="!searchLoading" :loading="searchLoading" @click="deviceinfoStartsearch"
                   icon="el-icon-search" >{{searchStr}}</el-button>
        <el-button type="danger" v-if="searchLoading" size="mini" style="margin-left: 10px" @click="manuallyStopSearch">{{this.i18n.t('stop search')}}</el-button>
      </div>
      <br>
      <!--          {{percentage}}-->
      <el-progress v-if="searchLoading" :show-text="false" color="#0666d2" :percentage="percentage"></el-progress>
      <br>
      <el-table
          ref="multipleTable"
          stripe
          height="400px"
          :data="tableData"
          :default-sort = "{prop: 'isBindding', order: 'ascending'}"
          @selection-change="handleTableSelectionChange"
          style="width: 100%">
        <el-table-column
            :selectable="selectable"
            type="selection"
            width="55">
        </el-table-column>
        <!--          设备序列号-->
        <el-table-column
            show-overflow-tooltip
            prop="deviceCode"
            :label="$t('Serial number')">
          <template slot-scope="scope">
            {{scope.row.deviceCode||'-'}}
          </template>
        </el-table-column>
        <!--          设备类型-->
        <el-table-column
            show-overflow-tooltip
            prop="address"
            :label="$t('Device type')">
          <template slot-scope="scope">
            <span>{{scope.row.deviceType===-1?$t('unknown'):$t(devOptions[scope.row.deviceType].label)}}</span>
          </template>
        </el-table-column>
        <!--          设备名称-->
        <el-table-column
            show-overflow-tooltip
            prop="deviceName"
            :label="$t('Device name')">
          <template slot-scope="scope">
            <span>{{scope.row.deviceName||'-'}}</span>
          </template>
        </el-table-column>

        <!--          MAC地址-->
        <el-table-column
            show-overflow-tooltip
            prop="mac"
            :label="$t('MAC address')">
          <template slot-scope="scope">
            <span>{{scope.row.mac||'-'}}</span>
          </template>
        </el-table-column>
        <!--          IP-->
        <el-table-column
            show-overflow-tooltip
            prop="ip"
            label="IP">
          <template slot-scope="scope">
            <span>{{scope.row.ip||'-'}}</span>
          </template>
        </el-table-column>
        <!--          端口-->
        <el-table-column
            show-overflow-tooltip
            prop="port"
            :label="$t('port')">
          <template slot-scope="scope">
            <span>{{scope.row.port}}</span>
          </template>
        </el-table-column>
        <!--          是否可用-->
        <el-table-column
            show-overflow-tooltip
            prop="available"
            sortable
            :label="$t('Availability or not')">
          <template slot-scope="scope">
<!--            可用-->
            <span v-if="scope.row.available" class="StatusText successStatusText">{{i18n.t('usable')}}</span>
<!--            不可用-->
            <span v-if="!scope.row.available" class="StatusText failStatusText">{{i18n.t('Not available')}}</span>
          </template>
        </el-table-column>
        <!--          是否绑定-->
        <el-table-column
            show-overflow-tooltip
            prop="isBindding"
            sortable
            :label="$t('Bind or not')">
          <template slot-scope="scope">
<!--          <span :style="{color:scope.row.isBindding==100?'#303030':scope.row.isBindding?'red':'#2e8245'}">{{scope.row|isBinddingFilter}}</span>-->
<!--          <span class="StatusText" :class="{'primaryStatusText':scope.row.isBindding==100,'successStatusText':!scope.row.isBindding}">{{scope.row|isBinddingFilter}}</span>-->
          <span class="StatusText" :class="scope.row|bindingStateStyle">{{scope.row|isBinddingFilter}}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <br>
    <div class="footBtnBox">
      <el-button size="small" type="handle" @click="handleCloseDialog" v-if="showCloseIcon">{{this.i18n.t('Cancel')}}</el-button>
      <el-button size="small" type="primary" :title="!selectRow.length?$t('Please check the device you want to add in the form!'):''" @click="submitForm" :disabled="!selectRow.length" :loading="saveLoading">{{this.i18n.t('Add')}}</el-button>
    </div>
    <dev ref='dev' @handleUpdate="submitTopForm" :editTableRow='editTableRow' :devFlag.sync='devFlag' v-if='devFlag'></dev>
  </el-dialog>
</template>

<script>
import {deviceTypeList} from '@/assets/common/js/utils/deviceConfig.js'
import { sbglGetDeviceid,sbglManualCreate,deviceinfoStartsearch,deviceinfoStopsearch } from '@/api/sbgl'

import dev from "./dev.vue";
import i18n from "@/lang/index"
//引入接口
export default {
  name: "searchDevice",
  provide(){
    return {
      // reload: this.reload
    }
  },
  filters:{
    bindingStateStyle(row){
      if (row.available){
        var isBindding= row.isBindding*1

        if (isBindding===0){
          // 未绑定
          return "successStatusText"
        }
        if (isBindding===1){
          // 已绑定
          return 'failStatusText'
        }
      }else{
        //未知
        return 'primaryStatusText'
      }
    },
    isBinddingFilter(row){
      if (row.available){
        var isBindding= row.isBindding*1

        if (isBindding===0){
          // 未绑定
          return i18n.t('Not yet bound')
        }
        if (isBindding===1){
          // 已绑定
          return i18n.t('Bound')
        }
      }else{
        //未知
        return i18n.t('unknown')
      }
    }
  },
  watch:{
    '$store.state.addDeviceList':{
      handler (newVal,oldVal) {
        //对数据执行操作
        console.log('设备列表变化了',newVal,oldVal)
        this.tableData=newVal
        console.log('表格数据',this.tableData);
      },
      deep: true // 深度监听
    },
    '$store.state.addDeviceListLoading':{
      handler (newVal,oldVal) {
        // debugger
        // console.log(60,newVal);
        //对数据执行操作
        this.searchLoading=newVal

        if (newVal==false){
          this.searchStr=this.i18n.t('search')
        }
        console.log('addDeviceListLoading变化了',newVal);
      },
      deep: true // 深度监听
    },
  },
  beforeDestroy() {
    // 离开页面时，清空store内的设备列表数据
    this.$store.commit('resetAddDeviceList',[])
    // 停止搜索设备
    this.deviceinfoStopsearch()
  },
  components: {
    dev,
  },
  data(){
    return{
      tableData:[],
      showCloseIcon:true,
      devFlag: false,
      editTableRow: null,
      percentage:0,
      saveLoading:false,
      devOptions:null,
      searchStr:this.i18n.t('In search...'),//搜索中...
      searchLoading:true,
      form:{
      },
      selectRow: [],
      isRouterAlive:true
    }
  },
  props: {
    searchFlag: {
      type: Boolean,
      default: false
    }
  },
  methods:{
    //复选框禁用
    selectable(row,rowIndex) {

      if(row.available&&this.devValidity(row)){
        return true;  //可用时不禁用
      }else {
        return false;  //禁用
      }
    },
    updateProgress(){
      var totalTime = 30000; // 30秒
      var interval = 1000; // 更新间隔
      var updateInterval=setInterval(()=>{
        this.percentage+=100/60
        if (this.percentage>=100){
          this.percentage=100
          clearInterval(updateInterval)
        }
      },1000)
    },
    // 刷新
    reload(){
      // this.isRouterAlive=false
      // this.$nextTick(()=>this.isRouterAlive=true)
    },
    // 刷新列表
    parentUpdate(){
      this.$emit("update:searchFlag",false);
      this.$parent.reset();
    },
    // 手动添加
    sbglManualCreate(params, num){
      // 隐藏关闭按钮
      this.showCloseIcon=false
      this.saveLoading=true
      sbglManualCreate(params).then((res) => {
        if (res.code === 200) {
          // 添加成功!
          this.W.$tips("success", this.i18n.t('Add successfully!'));
          if (num == 1) {

          }
          this.parentUpdate();
        }
      }).catch().finally(() => {
        // 恢复关闭弹窗按钮显示
        this.showCloseIcon=true
        // 关闭按钮loading状态
        this.saveLoading=false
      })
    },
    // 监控勾选操作
    handleTableSelectionChange(selection){
      console.log(selection);
      this.selectRow = selection;
    },
    // 关闭弹框
    handleCloseDialog(){
      this.$emit('update:searchFlag', false);
    },
    submitTopForm(params) {
      this.devFlag = false
      this.editTableRow = params

      var idItem=[]
      // var _this = this;
      this.selectRow.forEach(item=>{
        let params={
          deviceName:item.deviceName,
          deviceType:item.deviceType,
          ip:item.ip,
          deviceCode:item.deviceCode,
          username:this.editTableRow.username,
          password:this.editTableRow.password,
        }
        idItem.push(params);
      })
      // console.log(277, idItem);
      // console.log(278, this.editTableRow);
      for (const i in idItem) {
        this.sbglManualCreate(idItem[i], i+1==idItem.length ? 1 : 0)
      }
    },
    // 保存方法
    submitForm() {
      if(!this.selectRow.length){
        // 请在表格内勾选要添加的设备
        this.W.$tips("warning", this.i18n.t('Please check the device you want to add in the form!'));
      }else{
        // 确定要添加选择的设备吗
        this.W.$myConfirm('warning', this.i18n.t('Are you sure you want to add the selected device?'))
            .then(async () => {
              this.devFlag = true;
              this.editTableRow = null;
            })
            .catch(() => {

            });
      }
    },
    // 手动停止搜索设备
    manuallyStopSearch(){
      this.selectRow=[]
      // 停止搜索设备
      this.deviceinfoStopsearch()
      this.$store.commit('setAddDeviceListLoading',false)
      this.percentage=100

    },
    // 停止搜索设备
    deviceinfoStopsearch(){
      deviceinfoStopsearch().then(res => {
        if (res.code == 200) {

          // this.$refs.globalTable.loading_data()
        }
      }).catch().finally(()=>{

      })
    },
    // 开始搜索设备
    deviceinfoStartsearch(){
      this.$store.commit('setAddDeviceListLoading',true)
      this.percentage=0
      // 搜索中...
      this.searchStr=this.i18n.t('In search...')
      // 停止搜索设备
      // this.deviceinfoStopsearch()
      // 离开页面时，清空store内的设备列表数据
      this.$store.commit('resetAddDeviceList',[])
      deviceinfoStartsearch().then(res => {
        if (res.code == 200) {
          this.updateProgress()
          // this.$refs.globalTable.loading_data()
        }
      }).catch().finally(()=>{

      })
    },
    // 设备有效性检测
    devValidity(row){
      var state=false
      for (var i=0;i<this.devOptions.length;i++){
        if (this.devOptions[i].value==row.deviceType){
          state=true
          break
        }
      }
      return state
    },
  },
  mounted(){

    this.devOptions=deviceTypeList
    console.log(190,this.devOptions);
    this.deviceinfoStartsearch()
    // this.$nextTick(async () => {
    //     this.$refs.devListTable.loading_data(this.form)
    // });
  }
}
</script>

<style scoped>

</style>
